package csel.controller.listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import csel.controller.bindings.ActionBindings;
import csel.controller.decoders.EventDecoder;
import csel.controller.events.Action;

/**
 * Purpose: This defines the listener for action events, such as button clicks.
 * It creates a worker thread to process events
 * 
 * @author Nikolas Wolfe
 */

public class ActionEventListener implements ActionListener
{
	private final Thread decoder;
	private final EventDecoder<Action> eventDecoder;
	private final ActionBindings actionBindings;
	
	public ActionEventListener(EventDecoder<Action> ed, ActionBindings actionBindings)
	{
		this.actionBindings = actionBindings;
		this.eventDecoder = ed;
		this.decoder = new Thread(eventDecoder);
	}
	
	public void startDecoder()
	{
		decoder.start();
	}
	
	public void stopDecoder()
	{
		decoder.interrupt();
	}
	
	public void actionPerformed(ActionEvent e)
	{
		Action action = new Action(e, actionBindings);
		try
		{
			if(actionBindings.containsKey(e.getActionCommand()))
			{
				eventDecoder.registerEvent(action);
			}
		} catch (InterruptedException e1)
		{
			Thread.currentThread().interrupt();
		}
	}
}
